package com.pfzy.liveeventbusdemo.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus
import com.pfzy.liveeventbusdemo.LiveEventBusDemo

/**
 *
 */
class IpcService : Service() {
    override fun onCreate() {
        super.onCreate()
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST, String::class.java)
            .observeForever(observer)
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST_IN_APP, String::class.java)
            .observeForever(observer)
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST_GLOBAL, String::class.java)
            .observeForever(observer)
    }

    override fun onDestroy() {
        super.onDestroy()
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST, String::class.java)
            .removeObserver(observer)
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST_IN_APP, String::class.java)
            .removeObserver(observer)
        LiveEventBus
            .get(LiveEventBusDemo.KEY_TEST_BROADCAST_GLOBAL, String::class.java)
            .removeObserver(observer)
    }

    @Nullable
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    private val observer: Observer<String> = object : Observer<String> {
        override fun onChanged(@Nullable s: String?) {
            Toast.makeText(this@IpcService, s, Toast.LENGTH_SHORT).show()
        }
    }
}
